﻿var dropdown = '';
chrome.extension.sendRequest({'action': 'getDropdown'},function(response){
	dropdown = response.dropdown;
});
var dropdownArrow = ' <span class="status_dropdown_arrow">▼</span>';

var setClass = function(el, css)
{
	$(el).attr('class','');
	$(el).addClass(css.toLowerCase());
}

var StatusDropdown = function(row, project){
	var statusCell = $($(row).children('td')[1]).children('strong');
	chrome.extension.sendRequest({'action': 'getOption', 'option': project, 'status': $(statusCell).text()},function(response){

		if ($($(row).children('td')[5]).text().indexOf('Failed') > 0)
		{
			setClass(row, 'proj-failed');
		}
		else
		{
			setClass(row, 'proj-'+ response.replace(' ','').match(/([a-z]+)/gi).toString().toLowerCase());
		}

		$(statusCell).html(response +'!'+ dropdownArrow);
		$('.backings').trigger("update")
	});
};

var dateEnding = function(input, backed){
	var backed = new Date(backed).getFullYear();
	var str = $(input).text().replace(/sunday|monday|tuesday|wednesday|thursday|friday|saturday/gi, '').replace(',', ', '+backed);

	var ts = Date.parse(str.substring(0, str.indexOf(backed) + 4));

	return '<span style="display:block;height:0px;overflow:hidden;width:0px;">'+ ts +'</span>'+ str.substring(0, str.indexOf(backed) + 4) +'<br />'+ str.substring(str.lastIndexOf(backed) + 4);
};

var BackingTable = function(){
	$('.backings').each(function(){
		pledgeHeader = $(this).find('th')[3];
		$(pledgeHeader).html('Pledged');

		$(pledgeHeader).after('<th>Date Backed</th>')

		$(this).find('tbody tr').each(function(i, row){
			var url = $(this).find('td.first a').attr('href');
			var project = url.substring(url.lastIndexOf('/') + 1);
			var status = $($(row).children('td')[1]).children('strong');

			if ($($(row).children('td')[1]).text() == 'FUNDED!')
			{
				status.css({
					display: 'inline-block',
					position: 'relative',
					width:73
				});
				status.attr('data-id', project);
				status.html(StatusDropdown(row, project));
			}

			if ($($(row).children('td')[1]).text() == 'Unsuccessful')
			{
				$($(row).children('td')[4]).html('Cancelled');
			}

			pledgeCell = $(row).children('td')[3];
			backed = $(pledgeCell).children('span').html().replace(/\((.+)\)/, "$1");
			$(pledgeCell).after('<td>'+ backed +'</td>');
			$(pledgeCell).html('<strong>'+ $(pledgeCell).children('strong').html() +'</strong>');

			dateCell = $(row).children('td')[2];
			$(dateCell).html(dateEnding(dateCell, backed));
		});

		$(this).find('th').each(function(){
			$(this).append('<span/>');
		});

		$(this).tablesorter({sortList: [[4,1]]});
	});

	////////////////////////////////////////////////////////////////////////////

	var pledged = collected = outstanding = returned = total = 0.0;

	$($('.backings tbody')[0]).find('tr').each(function(i, row){
		status = $($(row).children('td')[1]).children('strong').text();
		pledge = parseFloat($($(row).children('td')[3]).find('strong').text().replace('$', ''));
		banked = $($(row).children('td')[5]).text().split('<br>')[0].replace(/^\s+|\s+$/g, '');

		switch(status)
		{
			case 'In Progress':
			pledged += pledge;
			break;

			case 'FUNDED!':
			if (banked.indexOf('Collected') != -1)
			{
				collected += pledge;
			}
			else if (banked.indexOf('Failed') != -1)
			{
				returned += pledge;
			}
			else
			{
				outstanding += pledge;
			}
			break;

			case 'Unsuccessful':
				returned += pledge;
			break;
		}
		setClass(row, 'proj-'+ status.replace(' ','').match(/([a-z]+)/gi).toString().toLowerCase());
		total += pledge;
	});

	$('.backings').after('<table class="backings funding"/>');
	$('.funding').append('<thead><tr><th>Pledged</th><th>Collected</th><th>Outstanding</th><th>Returned</th><th> </th></tr></thead>');
	$('.funding').append('<tbody><tr><td>$'+ pledged +'</td><td>$'+ collected +'</td><td>$'+ outstanding +'</td><td>$'+ returned +'</td><td>$'+ total +'</td></tr></tbody>');
};

$(document).ready(function(){
	BackingTable();

	$('span.status_dropdown_arrow').live({
		mouseenter: function(){
			$(this).css('color', '#454545');
			$(this).append(dropdown);
		},
		mouseleave: function(){
			$(this).css('color', '#999');
			$(this).children('.status_dropdown').remove();
		}
	});

	$("span.status_dropdown_arrow .status_dropdown a").live('click', function(event){
		var project = $(this).parents('strong[data-id]').attr('data-id');
		var text = $(this).text();
		chrome.extension.sendRequest({'action': 'setOption', 'option': project, 'value': text},function(){
			$(event.target).parents('strong[data-id]').html(text +'!'+ dropdownArrow);
		});
		setClass($(this).parents('tr'), 'proj-'+ text);
	});
});